const express = require("express");
const bodyParser = require("body-parser");

const {addUser,findUser,findid} = require("../handleUser")

const router = new express.Router();


//处理post请求
router.use(bodyParser.urlencoded())

//router.use("/register",bodyParser.urlencoded())
router.post("/register",(request,response)=>{
    //得到请求传递的参数
    const {username,password} = request.body;
    //新增用户
    addUser(username,password)
    .then(
        ()=>{
            //新增成功
            response.json({
                status: 0,
                message: "注册成功"
            })
        },
        ()=>{
            //新增失败
            response.status(200).json({
                status: 1,
                message: "注册失败，该用户已存在"
            })
        }
    )
})

//router.use("/login",bodyParser.urlencoded())
router.post("/login",(request,response)=>{
    //得到请求传递的参数
    const {username,password} = request.body;
    //登录 判断用户是否存在 密码是否正确
    findUser(username,password)
    .then(
        (result)=>{//登录成功
            //登录成功时设置cookie，保存用户登录状态，将(id 时间戳 过期时间)加密后，保存在cookies中
            response.cookie.set("userID",result);

            response.json({
                status: 0,
                message: "登录成功"
            })
        },
        ()=>{
            response.status(200).json({
                status: 1,
                message: "登录失败，用户名或密码错误！"
            })
        }
    )
})


module.exports = router;